<template>
	<div class="addBox">
		<div class="addBoxTop">
			<span>限时优惠</span>
		</div>
		<div class="addDiv">
			<el-form ref="formRef" :model="objectForm" :rules="objectRules" label-width="140px">
				<el-form-item label="使用云店" prop="shopid_yd">
					<el-select v-model="objectForm.shopid_yd" placeholder="请选择">
						<el-option v-for="item in getNewYunShopList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="活动标题" prop="title">
					<el-input v-model="objectForm.title" class="input-w" placeholder="请填写活动标题名称, 20个文字内" maxlength="20"
						show-word-limit></el-input>
				</el-form-item>
				<el-form-item label="活动描述" prop="desc">
					<el-input v-model="objectForm.desc" class="input-w" placeholder="请填写活动描述, 50个文字内" maxlength="50"
						show-word-limit></el-input>
				</el-form-item>
				<el-form-item label="标题开关">
					<div class="switchDiv">
						<el-switch v-model="objectForm.title_is_value"></el-switch>
						<span class="ml10 font_black7">关闭后云店不可见</span>
					</div>
				</el-form-item>
				<el-form-item label="限定人群" prop="ctype">
					<el-select v-model="objectForm.ctype" placeholder="请选择">
						<el-option v-for="item in limitCrowdList" :key="item.value" :label="item.label"
							:value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="活动时效" prop="objectTime">
					<el-date-picker v-model="objectForm.objectTime" @change="timestampFun" type="daterange"
						:clearable="false" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="活动说明">
					<el-input type="textarea" v-model="objectForm.txt_info" class="input-w" placeholder="请填写活动说明"
						show-word-limit></el-input>
				</el-form-item>
				<el-form-item label="活动规则">
					<el-input type="textarea" v-model="objectForm.txt_rule" class="input-w" placeholder="请填写活动规则"
						show-word-limit></el-input>
				</el-form-item>
				<el-form-item label="活动模版">
					<div class="active-box">
						<div class="mb-box flex_row">
							<div class="title font_black7 mr20">背景音乐</div>
							<el-select v-model="objectForm.music" placeholder="请选择">
								<el-option v-for="(item, index) in musicList" :key="index" :label="item.title"
									:value="item.id">
								</el-option>
							</el-select>
						</div>
						<div class="mb-box flex_row mt20">
							<div class="title font_black7 mr20">背景设置</div>
							<PickerModel :showTitle="true" :mode="pickerMode" :photoList="photoList"
								@modeChange="modeChange" @update:photoList="updatePhotoList" :color="selectedColor"
								:imgLimit="2" :isUpload="true" :delImg="false" @colorChange="colorSetChange" />
						</div>
						<div class="flex_row mt10">
							<div class="title font_black7 mr20">风格颜色</div>
							<PickerModel :showTitle="false" :mode="2" :color="objectForm.tpl_color_fill"
								:isUpload="false" @colorChange="colorChange" />
						</div>
						<div class="mb-box flex_row mt20">
							<div class="title font_black7 mr20">排列方式</div>
							<TplOrsort :tpl_ls="objectForm.tpl_ls" :tplShow="true" :disabled="false"
								@changeTplOrsort="changeTplOrsort('tpl_ls', $event)" />
						</div>
						<div class="mb-box flex_row mt20">
							<div class="title font_black7 mr20">排序方式</div>
							<TplOrsort :sort_type="objectForm.sort_type" :sortShow="true" :disabled="false"
								@changeTplOrsort="changeTplOrsort('sort_type', $event)" />
						</div>
					</div>
				</el-form-item>
				<el-form-item label="商品/项目">
					<div>
						<chiceSku ref="chiceSkuRef" :idyun="objectForm.shopid_yd" :list="objectForm.gd_ls" :title="`商品`"
							:type="'goods'" @item-change="itemChange">
						</chiceSku>
					</div>
					<div class="mt10">
						<chiceSku ref="chiceSkuRef2" :idyun="objectForm.shopid_yd" :list="objectForm.gd_ls2"
							:title="`项目`" :type="'project'" @item-change="item2Change">
						</chiceSku>
					</div>

				</el-form-item>
				<el-form-item label="启用">
					<div class="switchDiv">
						<el-switch v-model="objectForm.value1"></el-switch>
					</div>
				</el-form-item>
			</el-form>
			<div style="height: 50px;"></div>
		</div>
		<div class="addDivBtn">
			<div @click="createActivity" v-if="box_index_skey != 3">提交活动 （已选 {{ goodNum }}）</div>
			<div class="back-btn" @click="goBack" v-if="goBackSta">返回</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, defineProps, defineEmits, watch, computed } from '@vue/composition-api'
import config from "@/js/conf/Config.js"
import chiceSku from "@/components/commV2/chiceSku/index.vue"
import PickerModel from '@/components/commV2/pickerModel/index.vue'
import TplOrsort from "@/components/commV2/tplOrsort/index.vue";

// 定义组件 props
const props = defineProps({
	getYunShopList: {
		type: Array,
		default: () => []
	},
	detailID: {
		type: [Number, String],
		default: ''
	},
	box_index_key: {
		type: [Number, String],
		default: ''
	}
})

const box_index_skey = ref(props.box_index_key)
watch(() => props.box_index_key, (newVal) => {
	box_index_skey.value = newVal
}, { immediate: true, deep: true })

// 获取当前组件实例
const { proxy } = getCurrentInstance()

// 表单引用
const formRef = ref(null)

// 表单数据
const objectForm = ref({
	act: "add", // 活动类型
	id: "", // 活动id 
	shopid_yd: "", // 云店id
	title: "", // 活动标题
	desc: "", // 活动描述
	title_is: 1, // 标题描述
	title_is_value: false, // 标题描述
	ctype: 1, // 限定人群
	objectTime: "", // 日期数组
	time_from: "", // 开始日期
	time_to: "", // 结束日期
	txt_info: "", // 活动说明
	txt_rule: "", // 活动规则
	music: "1", // 背景音乐 音乐id
	tpl_color: "1", // 模板-颜色；1红2绿3蓝4紫
	tpl_ls: "1", // 模板-排列方式
	sort_type: "1", //  模板-排列顺序；
	gd_ls: [], // 产品
	gd_ls2: [], // 项目
	tpl_color1: "", // 风格颜色
	tpl_color_fill: "", // 风格颜色
	status: 1, // 状态
	value1: false // 启用状态
})

const goBackSta = computed(() => {
	return objectForm.value.act == 'add' || objectForm.value.act == 'edt'
})

// 获取活动详情
const getEventInfo = async () => {
	let param = {
		id: props.detailID,
	}
	try {
		let res = await proxy.$api({ url: config.YX_XS_EVENT_INFO, data: param })
		let result = res.data
		if (res.status == 1 && result) {
			objectForm.value = {
				...result,
				act: "edt",
				ctype: Number(result.ctype),
				time_from: result.time_from_txt,
				time_to: result.time_to_txt,
				objectTime: [result.time_from_txt, result.time_to_txt],
				pickerMode: result.tpl_ad && result.tpl_ad[0]?.obj_color ? 2 : 1,
				value1: result.status == 2 ? true : false, // 启用状态
				music: result.music.id,
				title_is_value: result.title_is == 2 ? true : false,
			}
			// 商品处理
			if (result.gd_ls && result.gd_ls.length > 0) {
				objectForm.value.gd_ls = goodsDataClassify(result.gd_ls)
			}
			// 项目处理
			if (result.gd_ls2 && result.gd_ls2.length > 0) {
				objectForm.value.gd_ls2 = result.gd_ls2
			}

			if (result?.tpl_ad && result.tpl_ad.length > 0) {
				// 如果有图片数据，则设置为图片模式
				if (!result.tpl_ad[0]?.obj_color) {
					photoList.value = result.tpl_ad.map(item => ({
						obj_type: item?.obj_type,
						name: item?.obj_img_rel,
						url: item?.obj_img,
						id: item?.obj_id
					}))
				} else {
					// 如果有颜色数据，设置为颜色模式
					selectedColor.value = `#${result.tpl_ad[0]?.obj_color || 'ffffff'}`
				}
			} else {
				// 如果没有数据，清空photoList
				photoList.value = []
			}
			pickerMode.value = result?.tpl_ad && result?.tpl_ad[0]?.obj_color ? 2 : 1;
			objectForm.value.tpl_color_fill = `#${result.tpl_color1 || 'ffffff'}`
		}
	} catch (error) { }
}

const itemChange = (newList) => {
	objectForm.value.gd_ls = newList
}

const item2Change = (newList) => {
	objectForm.value.gd_ls2 = newList
}

// 表单验证规则
const objectRules = ref({
	shopid_yd: [
		{ required: true, message: '请选择云店', trigger: 'change' }
	],
	title: [
		{ required: true, message: '请输入活动标题', trigger: 'blur' },
	],
	desc: [
		{ required: true, message: '请输入活动描述', trigger: 'blur' },
	],
	ctype: [
		{ required: true, message: '请选择限定人群', trigger: 'change' }
	],
	objectTime: [
		{ required: true, message: '选择活动时效', trigger: 'blur' },
	],
})


// 限定人群
const limitCrowdList = ref([
	{
		value: 1,
		label: '所有客户'
	},
	{
		value: 2,
		label: '新客首次购买'
	}
])

// 选择背景音乐
const musicList = ref([])
const pickerMode = ref(1)
const selectedColor = ref(null)
const photoList = ref([])

// 选择日期
const timestampFun = (e) => {
	if (!e) {
		objectForm.value.objectTime = ""
		objectForm.value.time_from = ""
		objectForm.value.time_to = ""
		return
	}
	objectForm.value.time_from = objectForm.value.objectTime[0]
	objectForm.value.time_to = objectForm.value.objectTime[1]
}

// 表单验证
const submitForm = (formName) => {
	formRef.value.validate(async (valid) => {
		if (valid) {
			const photosList = photoList.value
			if (pickerMode.value == 1 && photosList.length < 2) {
				proxy.$message.error('请上传至少2张广告背景图片')
				return
			}
			if (pickerMode.value == 2 && !selectedColor.value) {
				proxy.$message.error('请选择广告背景颜色')
				return
			}
			let tpl_ad = []
			if (pickerMode.value == 1) {
				tpl_ad = photoList.value.map(item => ({
					obj_color: "",
					obj_type: "",
					obj_img: item.name,
					obj_id: item.id,
					obj_img_rel: item.url
				}))
			} else {
				let obj1_color = selectedColor.value.replace('#', '')
				obj1_color = obj1_color.startsWith('#') ? obj1_color.substring(1) : obj1_color
				tpl_ad = [{
					obj_color: obj1_color,
					obj_type: "",
					obj_img: "",
					obj_id: "",
					obj_img_rel: ""
				}]
			}
			if (!goodNum.value) return proxy.$message.error('至少选择一个产品或服务。')
			let param = {
				...objectForm.value,
				tpl_color1: objectForm.value.tpl_color_fill.replace('#', ''),
				tpl_color2: objectForm.value.tpl_color_fill.replace('#', ''),
				tpl_ad,
				status: objectForm.value.value1 ? 2 : 1, // 状态
				title_is: objectForm.value.title_is_value ? 2 : 1,
			}
			try {
				let res = await proxy.$api({ url: config.YX_XS_EVENT_SAVE, data: param })
				if (res.status == 1) {
					proxy.$message.success("操作成功")
					emit("addOrEdt", {
						type: objectForm.value.act,
						status: objectForm.value.value1 ? 2 : 1,
						id: props.detailID || ''
					})
				}
			} catch (error) {
				console.error('操作失败:', error)
			}
		} else {
			console.log('error submit!!')
			return proxy.$message.error("请检查表单内容")
		}
	})
}


const goodNum = computed(() => {
	return (objectForm.value.gd_ls?.length || 0) + (objectForm.value.gd_ls2?.length || 0)
})

//  创建活动
const createActivity = () => {
	submitForm("form")
}

const getMusicList = async () => {
	try {
		let res = await proxy.$api({ url: config.YX_PIN_MUSIC_LS, data: {} })
		if (res.status == 1 && res.data.music_ls) {
			musicList.value = res.data.music_ls
		}
	} catch (error) {
		console.error('获取音乐列表失败:', error)
	}
}

const goodsDataClassify = (data) => {
	let mapArr = data.map(item => {
		return {
			...item, // 目前格式无需处理，若有处理的在扩展
		}
	})
	return mapArr
}

const restFun = () => {
	// 重置表单验证
	formRef.value?.resetFields()

	// 重置 objectForm 到初始状态
	objectForm.value = {
		act: "add", // 活动类型
		id: "", // 活动id 
		shopid_yd: "", // 云店id
		title: "", // 活动标题
		desc: "", // 活动描述
		title_is: 1, // 标题描述
		title_is_value: false, // 标题描述
		ctype: 1, // 限定人群
		objectTime: "", // 日期数组
		time_from: "", // 开始日期
		time_to: "", // 结束日期
		txt_info: "", // 活动说明
		txt_rule: "", // 活动规则
		music: "1", // 背景音乐 音乐id
		tpl_color: "1", // 模板-颜色；1红2绿3蓝4紫
		tpl_ls: "1", // 模板-排列方式
		sort_type: "1", //  模板-排列顺序；
		gd_ls: [], // 产品
		gd_ls2: [], // 项目
		tpl_color1: "", // 风格颜色
		tpl_color_fill: "", // 风格颜色
		status: 1, // 状态
		value1: false // 启用状态
	}
	// 重置其他相关状态
	pickerMode.value = 1
	photoList.value = []
	selectedColor.value = '#409EFF'
}

// 定义组件 emits
const emit = defineEmits(['addOrEdt'])
const goBack = () => {
	emit("addOrEdt", {
		type: 'back',
		status: box_index_skey.value,
		id: props.detailID || ''
	})
}

const modeChange = (newMode) => {
	pickerMode.value = newMode
}
const updatePhotoList = (newList) => {
	photoList.value = [...newList]
}
const colorSetChange = (newColor) => {
	selectedColor.value = newColor
}
const colorChange = (newColor) => {
	objectForm.value.tpl_color_fill = newColor
	objectForm.value.tpl_color1 = newColor.replace('#', '')
}
const changeTplOrsort = (type, e) => {
	if (type == 'tpl_ls') {
		objectForm.value.tpl_ls = e.tpl_ls
	} else if (type == 'sort_type') {
		objectForm.value.sort_type = e.sort_type
	}
}
defineExpose({
	restFun,
	objectForm,
	getEventInfo
})

onMounted(() => {
	getMusicList() // 获取背景音乐
})

watch(() => props.detailID,
	(newVal) => {
		if (newVal) {
			getEventInfo()
		}
	},
	{ deep: true, immediate: true }
)
const getNewYunShopList = ref(props.getYunShopList)
watch(
	() => props.getYunShopList,
	(newVal) => {
		if (newVal && newVal.length > 2) {
			// 删除数组第一个对象
			getNewYunShopList.value = newVal.slice(1)
		}
	},
	{ deep: true, immediate: true }
)

</script>

<style lang="scss" scoped>
.addBox {
	width: 100%;
	box-sizing: border-box;

	.addDivBtn {
		width: 100%;
		height: 60px;
		line-height: 60px;
		text-align: right;
		border-top: 1px solid #E4E7ED;

		>div {
			display: inline-block;
			background: #3388ff;
			font-size: 16px;
			height: 100%;
			color: #FFFFFF;
			text-align: center;
			padding: 0 20px;
			cursor: pointer;
			border-right: 1px solid #FFFFFF;

			&:last-child {
				border: none;
			}
		}

		.back-btn {
			background: #ece8e8;
			color: #333;
			border-right: 1px solid #ececec;
		}
	}

	.addBoxTop {
		width: 100%;
		height: 40px;
		border-bottom: 2px solid #E4E7ED;
		margin-bottom: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;

		span {
			font-size: 20px;
		}

		>div {
			height: 28px;
		}
	}

	.addDiv {
		box-sizing: border-box;
		width: 100%;
		padding-right: 100px;
		height: calc(100vh - 57px - 70px);
		overflow-y: auto;

		.switchDiv {
			height: 40px;
			display: flex;
			align-items: center;

			span {
				margin-right: 20px;
			}
		}
	}

	.active-box {
		background-color: #f1f5f9;
		padding: 20px 30px;
		border-radius: 8px;
		border: 1px solid #e2e8f0;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

		.mb-box {
			margin-bottom: 0;
		}

		::v-deep .el-radio-group {
			height: 40px !important;
			display: flex !important;
			align-items: center;
		}
	}

	::v-deep.mb-box {
		margin-bottom: 10px;

		&:last-child {
			margin: 0;
		}

		.el-radio__label {
			display: none;
		}

		.pl-box {
			font-size: 14px;
			display: flex;
			align-items: center;
			cursor: pointer;

			img {
				margin-right: 10px;
				width: 16px;
				height: 16px;
			}

			.txt-box {
				display: flex;
				align-items: center;
			}
		}

		.color-box {
			display: flex;
			font-size: 14px;

			.color-row {
				margin-right: 10px;
				text-align: center;
				cursor: pointer;

				.color-title {
					font-size: 12px;
				}

				.background-item {
					width: 100px;
					height: 30px;
					border-radius: 5px;
				}
			}
		}
	}
}
</style>